package cn.cheneyjoo.controller;

import cn.cheneyjoo.DTO.ProductsDTO;
import cn.cheneyjoo.DTO.ResponseDTO;
import cn.cheneyjoo.Vo.ProductVo;
import cn.cheneyjoo.mapper.EsResultMapper;
import cn.cheneyjoo.model.Products;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ElasticsearchTemplate template;

    @PostMapping()
    public ResponseDTO searchProduct(ProductsDTO po) {
        // 原生查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 1.1 source过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[0], new String[0]));
        // 1.2搜索条件
        queryBuilder.withQuery(QueryBuilders.matchQuery("name", po.getName()));
        queryBuilder.withFilter(QueryBuilders.rangeQuery("price").gte(po.getFrom()).lt(po.getTo()));
        // 1.3分页及排序条件
        queryBuilder.withPageable(PageRequest.of((po.getPageIndex()-1)*po.getPageSize(), po.getPageSize(), Sort.by(Sort.Direction.ASC, "price")));
        // 1.4构建高亮查询
        HighlightBuilder.Field field = new HighlightBuilder.Field("name").preTags("<font style='color:red'>").postTags(" </font>");
        // 名字高亮
        queryBuilder.withHighlightFields(field);
        //构建查询条件，并且查询
        AggregatedPage<Products> result = template.queryForPage(queryBuilder.build(), Products.class, new EsResultMapper());
        // 2、解析结果：
        long total = result.getTotalElements();
        int totalPages = result.getTotalPages();
        List<Products> list = result.getContent();
        ProductVo productVo = new ProductVo();
        productVo.setResult(list);
        productVo.setTotalCount((int) total);
        productVo.setTotalPages(totalPages);
        return new ResponseDTO(200, "成功", productVo);
    }
}
